var mcAdminApp = angular.module('mcAdminApp', ['ngTable','ngRoute','ngDialog']);
// configure our routes
mcAdminApp.config(function($routeProvider) {
	$routeProvider
	.when('/news-letter', {
		templateUrl : 'newsletter.html',
		controller  : 'newsletterCntrl'
	})
	.when('/notifications', {
		templateUrl : 'notifications.html',
		controller  : 'notificationsCntrl'
	})
	.when('/admin-notification-history', {
		templateUrl : 'admin-notification-history.html',
		controller  : 'adminNotificationHistoryCntrl'
	})
	.when('/discounts', {
		templateUrl : 'discounts.html',
		controller  : 'discountsController'
	})
	.when('/reports', {
		templateUrl : 'reports.html',
		controller  : 'reportsController'
	})
	.when('/total-users-report', {
		templateUrl : 'total-users-report.html',
		controller  : 'totalUsersReportController'
	})
	.when('/shop-wise-reports', {
		templateUrl : 'shop-wise-reports.html',
		controller  : 'shopWiseReportsController'
	})
	.when('/total-users-orders', {
		templateUrl : 'total-users-orders.html',
		controller  : 'totalUsersOrdersController'
	})
	.when('/complaints', {
		templateUrl : 'complaints.html',
		controller  : 'complaintsCntrl'
	})
	.when('/reviews', {
		templateUrl : 'reviews.html',
		controller  : 'reviewsCntrl'
	})
	.when('/order-status', {
		templateUrl : 'order-status.html',
		controller  : 'orderStatusCntrl'
	})
	.when('/new-orders', {
		templateUrl : 'new-orders.html',
		controller  : 'newOrdersController'
	})
	.when('/all-users', {
		templateUrl : 'all-users.html',
		controller  : 'allUsers'
	})
	.when('/order-history', {
		templateUrl : 'order-history.html',
		controller  : 'orderHistoryController'
	})
	.when('/quotation-sent-orders', {
		templateUrl : 'quotation-sent-orders.html',
		controller  : 'quotationSentOrders'
	})
	.when('/', {
		templateUrl : 'login.html',
		controller  : 'adminLoginController'
	})
	.when('/account', {
		templateUrl : 'account.html',
		controller  : 'accountController'
	})
	.when('/add-shop', {
		templateUrl : 'add-shop.html',
		controller  : 'addShopController'
	})
	.when('/forgot-password', {
		templateUrl : 'forgoten.html',
		controller  : 'fpController'
	})
	.when('/reset-password', {
		templateUrl : 'reset-password.html',
		controller  : 'resetPwdController'
	})
	.when('/admin-all-shops', {
		templateUrl : 'all-shops.html',
		controller  : 'adminAllShopsController'
	})
	.when('/admin-shop-requests', {
		templateUrl : 'request-shop.html',
		controller  : 'adminShopRequestsController'
	})
	.when('/logout', {
		templateUrl : 'login.html',
		controller  : 'logoutController'
	})
	.when('/tommorow-renewal-orders', {
		templateUrl : 'tommorow-renewal-orders.html',
		controller  : 'tommorowRenewalOrdersController'
	})
	.when('/change-password', {
		templateUrl : 'change-password.html',
		controller  : 'changePasswordController'
	})
	.when('/renewal-orders', {
		templateUrl : 'renewal-orders.html',
		controller  : 'RenewalOrdersController'
	})
});
google.load('visualization', '1', {packages: ['corechart']});
//admin reports

//Active menu directive 
	mcAdminApp.directive('activeLink', ['$location', function(location) {
		return {
		  restrict: 'A',
		  link: function($scope, $element, $attrs, $controller) {
			var clazz = $attrs.activeLink;
			var path = $attrs.href;
			path = path.substring(1); //hack because path does not return including hashbang
			$scope.location = location;
			$scope.$watch('location.path()', function(newPath) {
			  if (path === newPath) {
				$element.addClass(clazz);
			  } else {
				$element.removeClass(clazz);
			  }
			});
		  }
		};
	}]); 
//End Active menu directive
mcAdminApp.controller('reportsController', function($scope,$sce,$http) {
		$scope.showChrt=true;
		$scope.loading		=	$sce.trustAsHtml('<img src="images/ajax-loader.gif"/>');
		$scope.getReportsPieChart = function() {
					var fromdate=$('#fromdate').val();
					var todate=$('#todate').val();
					var dataObj = {
						from_date:fromdate,
						to_date:todate,
						reports_type:'null'
					};
					$http.post(webServiceUrl+'totalreports',dataObj)
						.success(function(response) {
							$scope.loading		=	$sce.trustAsHtml('');
							if(response.reports1!=0 || response.reports2!=0 || response.reports3!=0 || response.reports4!=0){
									$scope.responseData=[
														  ['Pending Orders',response.reports1],
														  ['Proccessing Orders',response.reports2],
														  ['Proccessed Orders',response.reports3],
														  ['Cancelled Orders',response.reports4]
														];
							}else {
								$('#visualization').html('No reports....');
							}
						});
		  }
		$scope.dateFilter = function() {
			if($scope.showChrt==true){
				$scope.loading		=	$sce.trustAsHtml('<img src="images/ajax-loader.gif"/>');
				$scope.getReportsPieChart();
			}
		}
$scope.isValidDate = function (dateStr) {
    if (dateStr == undefined)
        return false;
    var dateTime = Date.parse(dateStr);

    if (isNaN(dateTime)) {
        return false;
    }
    return true;
};

$scope.getDateDifference = function (fromDate, toDate) {
    return Date.parse(toDate) - Date.parse(fromDate);
};

$scope.isValidDateRange = function (fromDate, toDate) {
    if (fromDate == "" || toDate == "")
	{
		$scope.showChrt=true;
        return true;
	}
    if (typeof fromDate !="undefined" && $scope.isValidDate(fromDate) == false) {
		$scope.showChrt=false;
        return false;
    }
    if ($scope.isValidDate(toDate) == true) {
        var days =$scope.getDateDifference(fromDate, toDate);
        if (days < 0) {
			$scope.showChrt=false;
            return false;
        }
    }
	$scope.showChrt=true;
    return true;
};

	
});
//End admin reports
mcAdminApp.directive("datepicker", function () {
  return {
    restrict: "A",
    require: "ngModel",
    link: function (scope, elem, attrs, ngModelCtrl) {
      var updateModel = function (dateText) {
        scope.$apply(function () {
          ngModelCtrl.$setViewValue(dateText);
        });
      };
      var options = {
        dateFormat: "dd/mm/yy",
        onSelect: function (dateText) {
          updateModel(dateText);
        }
      };
      elem.datepicker(options);
    }
  }
});
mcAdminApp.directive('dateLowerThan', ["$filter", function ($filter) {
    return {
        require: 'ngModel',
        link: function (scope, elm, attrs, ctrl) { 
           scope.validateDateRange = function (inputValue) {
                var fromDate = $filter('date')(inputValue, 'short');
                var toDate = $filter('date')(attrs.dateLowerThan, 'short');
                scope.isValid = scope.isValidDateRange(fromDate, toDate);
                ctrl.$setValidity('dateLowerThan',scope.isValid);
				if( fromDate!="" && toDate!="" && typeof fromDate !="undefined" && typeof toDate !="undefined" && scope.isValid )
				{
					scope.dateFilter();
				}
                return inputValue;
            };

            ctrl.$parsers.unshift(scope.validateDateRange);
            ctrl.$formatters.push(scope.validateDateRange);
            attrs.$observe('dateLowerThan', function () {
                scope.validateDateRange(ctrl.$viewValue);
            });
        }
    };
}]);

//Shop wise reports
mcAdminApp.controller('shopWiseReportsController', function($scope,$sce,$http) {
	$scope.getReportsPieChart = function() {
			var dataObj = {
							status:1,
							type_id:3
			};
			$http.post(webServiceUrl+'admin-all-shops',dataObj)
				.success(function(response) {
				if(response.value!=0){
						var getuserslist="";
						var obj =response.shopData;
						$.each(obj, function (index,Object){					
							getuserslist+='<option  value="'+Object.user_id+'">'+Object.user_name+'</option>';
						});
						$('#user_id').html(getuserslist);
						$scope.usersOrders();
					}
				});
	}		
	$scope.usersOrders = function() {
		var shop_id = $("#user_id").val();
		$http.get(webServiceUrl+'shop-com-rp-rv-rtng/shop-'+shop_id)
			.success(function(response) {
				$scope.ratingsHide=true;
				if(response.cntRating1!=0){
					$scope.stars1=response.cntRating1;
				}else{
					$scope.stars1=response.cntRating1;
				}if(response.cntRating2!=0 ){
					$scope.stars2=response.cntRating2;
				}else{
					$scope.stars2=response.cntRating2;
				}if(response.cntRating3!=0 ) {
					$scope.stars3=response.cntRating3;	
				}else{
					$scope.stars3=response.cntRating3;
				}if(response.cntRating4!=0) {
					$scope.stars4=response.cntRating4;
				}else{
					$scope.stars4=response.cntRating4;
				}if(response.cntRating5!=0){
					$scope.stars5=response.cntRating5;		
				}else{
					$scope.stars5=response.cntRating5;
				}
				if(response.cntRating5==0 && response.cntRating4==0 && response.cntRating3==0 && response.cntRating2==0 && response.cntRating1==0 ){
					$scope.ratingsHide=false;
				}
				if(response.cntComplanits!=0 || response.cntReplies!=0 || response.cntReviews!=0 ){
						$scope.responseData=[
											  ['Complaints',response.cntComplanits],
											  ['Repliesofcomplaints',response.cntReplies],
											  ['Reviews',response.cntReviews]
											];
				}else {
					$('#visualization').html('No reports....');
				}
		});
			var dataObj = {
					shop_id:shop_id
			};
			$http.post(webServiceUrl+'shop-orders',dataObj)
			.success(function(response) {
				if(response.totOrders!=0 || response.totrenewalOrders!=0 || response.totSentorders!=0 || response.totConfirmedOrders!=0 || response.totDeliveredOrders!=0 || response.totunPaidOrders!=0 || response.totPaidOrders!=0){
							$scope.responseData=[
												  ['TotalOrders',response.totOrders],
												  ['TotRenewalOrders',response.totrenewalOrders],
												  ['SentpriceToAdmin',response.totSentorders],
												  ['ConfirmedOrders',response.totConfirmedOrders],
												  ['DeliveredOrders',response.totDeliveredOrders],
												  ['DiscountsUnpaidToAdmin',response.totunPaidOrders],
												  ['DiscountsPaidToAdmin',response.totPaidOrders]
												];
				}else {
					$('#visualization').html('No reports....');
				}
			});
	}
	
	
});
//End Shop wise reports
//total users orders report
mcAdminApp.controller('totalUsersOrdersController', function($scope,$sce,$http) {
	$scope.getReportsPieChart = function() {
			var dataObj = {
					status:1,
					type_id:2
			};
			$http.post(webServiceUrl+'admin-all-shops',dataObj)
				.success(function(response) {
				if(response.value!=0){
						var getuserslist="";
						var obj =response.shopData;
						$.each(obj, function (index,Object){					
							getuserslist+='<option  value="'+Object.user_id+'">'+Object.user_name+'</option>';
						});
						$('#user_id').html(getuserslist);
						$scope.usersOrders();
					}
				});
				
	}		
	$scope.usersOrders = function() {			
		var user_id = $("#user_id").val();
		$http.get(webServiceUrl+'userreports/user-'+user_id)
			.success(function(response) {
				if(response.pending!=0 || response.processing!=0 || response.processed!=0 || response.cancelled!=0 ){
						$scope.responseData=[
											  ['PendingOrders',response.pending],
											  ['ProcessingOrders',response.processing],
											  ['ProcessedOrders',response.processed],
											  ['CancelledOrders',response.cancelled]
											];
				}else {
					$('#visualization').html('No reports....');
				}
			});
	}
});
//End total users orders report

mcAdminApp.controller('totalUsersReportController', function($scope,$sce,$http) {
		  $scope.getReportsPieChart = function() {
					$http.get(webServiceUrl+'total-users-report')
						.success(function(response) {
							if(response.shopusers!=0 || response.users!=0){
									$scope.responseData=[
														  ['ShopusersCount',response.shopusers],
														  ['UsersCount',response.users]
														];
							}else {
								$('#visualization').html('No reports....');
							}
						});
		  }
});
mcAdminApp.directive('chart', function() {
        return {
          restrict: 'E,A',
          link: function($scope, $elm, $attr) {
            // Create the data table.
			$scope.getReportsPieChart();
			$scope.$watch('responseData', function (newMyData) {

			
            var data = new google.visualization.DataTable();
            data.addColumn('string', 'Topping');
            data.addColumn('number', 'Slices');
			if(typeof newMyData!="undefined"){
				data.addRows(newMyData);
			}
            // Set chart options
            var options = {'title':'List of Shopusers and Users'};

            // Instantiate and draw our chart, passing in some options.
            var chart = new google.visualization.PieChart($elm[0]);
            chart.draw(data, options);
			});
          }
      }
    });
mcAdminApp.controller('notificationsCntrl', function($scope,$sce,$http,ngTableParams,ngDialog) {
	 $scope.viewreneorderNotifications = function (orderId,ordertype,usertype){
			$scope.changeNotificationStatus(orderId,1,ordertype,usertype,0);
	 }
	 $scope.vieworderNotifications = function (orderId,ordertype,usertype){
			$scope.changeNotificationStatus(orderId,2,ordertype,usertype,0);
	 }
	 $scope.viewComplaintNotifications = function (orderId,ordertype,usertype){
			$scope.changeNotificationStatus(orderId,3,ordertype,usertype,3);
	 }
	 $scope.viewShopNotifications = function (orderId,ordertype,usertype){
		    $scope.changeNotificationStatus(orderId,3,ordertype,usertype,3);
	 }
	 $scope.viewReviewNotifications = function (orderId,ordertype,usertype){
			$scope.changeNotificationStatus(orderId,4,ordertype,usertype,3);
	 }
	 $scope.viewUregNotifications = function (orderId,ordertype,usertype){
		   $scope.changeNotificationStatus(orderId,5,ordertype,usertype,1);
	 }
	 $scope.viewShopregNotifications = function (orderId,ordertype,usertype){
			$scope.changeNotificationStatus(orderId,6,ordertype,usertype,1);
	 }
	 $scope.viewSendPriceNotifications = function (orderId,ordertype,usertype){
			$scope.changeNotificationStatus(orderId,7,ordertype,usertype,3);
	 }
	 $scope.viewOrderConfirmedNotifications = function (orderId,ordertype,usertype){
		    $scope.changeNotificationStatus(orderId,8,ordertype,usertype,3);
	 }
	 $scope.viewrenewalConfirmedNotifications = function (orderId,ordertype,usertype){
		    $scope.changeNotificationStatus(orderId,9,ordertype,usertype,0);
	 }
	 
	 $scope.changeNotificationStatus = function (OrderId,type,ordertype,usertype,updatetype){
		 var dataObj = {
				OrderType:ordertype,
				userType:usertype,
				updatetype:updatetype
		 };
		 $http.put(webServiceUrl+'notifications/'+OrderId,dataObj)
		.success(function(response) {
			if(response.value==1){
				if(type==1){
					window.location="#/renewal-orders";
				}else if(type==2){
					window.location="#/new-orders";
				}else if(type==3){
					window.location="#/complaints";
				}else if(type==4){
					window.location="#/reviews";
				}else if(type==5){
					window.location="#/all-users";
				}else if(type==6){
					window.location="#/all-shops";
				}else if(type==7){
					window.location="#/quotation-sent-orders";
				}else if(type==8){
					window.location="#/order-history";
				}else if(type==9){
					window.location="#/new-orders";
				}
			}
		 });
	 }
	
	
	if(typeof sessionStorage["admin_user_id"]!='undefined'){
		$scope.data="";
		var type=1;
		var admin_user_id = JSON.parse(sessionStorage["admin_user_id"]);
		$http.get(webServiceUrl+'notifications/'+type+'-'+admin_user_id)
		.success(function(response) {
			if(response.count!='0'){
				var data=response.notifications;
				$scope.getNotifications(admin_user_id);
				$scope.tableParams = new ngTableParams({
					page: 1, 
					count: 10
				}, {
					total: data.length,
					getData: function($defer, params) {
						$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
					}
				});
			}else{
				$scope.emptyOrders=errornodata_message;
			}
		});
	}else{
		location.href="#";
	}
});
mcAdminApp.controller('adminNotificationHistoryCntrl', function($scope,$sce,$http,ngTableParams,ngDialog) {
	if(typeof sessionStorage["admin_user_id"]!='undefined'){
		$scope.data="";
		var admin_user_id = JSON.parse(sessionStorage["admin_user_id"]);
		var dataObj = {
				usertype:1,
				user_id:admin_user_id
		};
		$http.post(webServiceUrl+'notifications',dataObj)
		.success(function(response) {
			if(response.value!=0){
				var data=response.noitifications;
				$scope.getNotifications(admin_user_id);
				$scope.tableParams = new ngTableParams({
					page: 1,            // show first page
					count: 10           // count per page
				}, {
					total: data.length, // length of data
					getData: function($defer, params) {
						$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
					}
				});
			}else{
				$scope.tableParams='There are no data';
			}
		});
	}else{
		location.href="#";
	}
});
mcAdminApp.controller('newsletterCntrl', function($scope,$sce,$http,ngTableParams,ngDialog) {
	$scope.notis={};
	var flag=true;
	CKEDITOR.replace('message', {});
	$scope.valid_messageform2 = function() {
		var txtSubj=$scope.subject;
		if(txtSubj==undefined){
			$scope.errorSubject=newsletter_subject_message; 
			flag=false;
		}else{
			$scope.errorSubject=''; 
		}
		$('textarea[name="message"]').val(CKEDITOR.instances.message.getData());
		var desc=$('#message').val().replace("<p>","");
		desc=desc.replace("</p>","");
		if(desc=="")
		{
			$scope.errorMessage=newsletter_description_message; flag=false;
		}else{
			$scope.errorMessage=''; 
		}
		if(flag==true){
			var dataObj = {
				subject			:	txtSubj,
				message			:	desc
			};
			$http.post(webServiceUrl+'sendnewsletter',dataObj)
			.success(function(response) {
				if(response.value==1){
					$("#successmsg").addClass("success").html(newsletter_success_message).fadeIn('slow').delay(3000).fadeOut('slow');
					$("#subject").val('');						
					$('#message').val('');
				}else{
					$("#successmsg").html(response.status);
				}
			});
		}
	};
	
});
mcAdminApp.controller('complaintsCntrl', function($scope,$sce,$http,ngTableParams,ngDialog) {
	$scope.notis={};
	$http.get(webServiceUrl+'all-complaints')
	.success(function(response) {
		$scope.notis=response.result;
	});
});
mcAdminApp.controller('reviewsCntrl', function($scope,$sce,$http,ngTableParams,ngDialog) {
	$scope.errornodata_message="";
	$http.get(webServiceUrl+'reviews-and-ratings')
	.success(function(response) {
	if(response.value!=0){
			var data=response.result;
			var html="";
			var rhtml="";
			$.each(data, function (index,Object) {
				html+='<div class="media">';
				html+='<a class="pull-left" href="#">';
				html+='<img src="https://lh3.googleusercontent.com/uFp_tsTJboUY7kue5XAsGA=w48-c-h48" class="media-object img_profile"></a>';		  
				html+='<div class="media-body">';
				var rating=Object.rating;
				for(var i=1;i<=rating;i++){
					rhtml+='<img class="star" src="images/green-star.png">';
				}for(var j=i;j<=5;j++){
					rhtml+='<img class="star" src="images/gray-star.png">';
				}
				html+='<h4>'+rhtml+'</h4>';
				if(Object.shop_name!=null){
				html+='<h4 class="media-heading">'+Object.user_name+' To '+Object.shop_name+ ' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Tracking ID: '+Object.tracking_id+'</h4>';
				}else{
				html+='<h4 class="media-heading">'+Object.user_name+' &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Tracking ID: '+Object.tracking_id+'</h4>';
				}
				html+= '<p>'+ Object.review + '</p>';	 	 
				html+='</div>'; 
				html+='</div>';
				rhtml="";
			});
		}else{
			$scope.errornodata_message=errornodata_message;
		}
		$scope.revieww		=	$sce.trustAsHtml(html);
		
	});
});
mcAdminApp.controller('orderStatusCntrl', function($scope,$sce,$http) {
	$scope.Findorderstatus =function(){
		var trId = $scope.orderTrackId;
		if(trId==undefined){
		   $scope.errorMessage=Orderstatustrack_id;
		   return false;   
		}else if(isNaN(trId)){
			$scope.errorMessage=Orderstatustracking_id_number;		
		    return false;  
		}else{
		  $scope.errorMessage="";
		}
		$('#orderStatusReload').html('<img src="images/ajax-loader.gif"/>');
		var user_id = JSON.parse(sessionStorage["admin_user_id"]);
		$http.get(webServiceUrl+'order-status/order_status-'+trId)
		.success(function(data) {
			$('#orderStatusReload').html('');
			$("#orderTrackId").val("");
			if(data.value==0){
				$('#success_alert').show();
				$scope.orderStatusId=Orderstatus_pending;
				$("html, body").animate({ scrollTop: 0 }, 600);
				$('#success_alert').delay(3000).fadeOut('slow');
				$('#error_alert').hide();
			}else if(data.value==1){
				$('#success_alert').show();
				$scope.orderStatusId=Orderstatus_processing;
				$("html, body").animate({ scrollTop: 0 }, 600);
				$('#success_alert').delay(3000).fadeOut('slow');
				$('#error_alert').hide();
			}else if(data.value==2){
				$('#success_alert').show();
				$scope.orderStatusId=Orderstatus_processed;
				$("html, body").animate({ scrollTop: 0 }, 600);
				$('#success_alert').delay(3000).fadeOut('slow');
				$('#error_alert').hide();
			}else if(data.value==3){
				$('#success_alert').show();
				$scope.orderStatusId=Orderstatus_cancelled;
				$("html, body").animate({ scrollTop: 0 }, 600);
				$('#success_alert').delay(3000).fadeOut('slow');
				$('#error_alert').hide();
			}else{
				$('#error_alert').show();
				 $scope.orderStatusIdError=Orderstatus_error_message;
				$("html, body").animate({ scrollTop: 0 }, 600);
			}
		});
	};
	
});
mcAdminApp.controller('discountsController', function($scope,$sce,$http,ngTableParams,ngDialog) {
	$scope.errornodata_message="";
	$scope.paidDiscount = function(user_m_id) {
		$http.put(webServiceUrl+'discounts/'+user_m_id)
		.success(function(response) {
			if(response.output=='success'){
				$('#paidStatus'+user_m_id).html('');
				$('#paidStatus'+user_m_id).append('Paid');
				$('#paidDis'+user_m_id).html('');
				$('#paidDis'+user_m_id).append('Completed');
			}
		});
	};
	if(typeof sessionStorage["admin_user_id"]!='undefined'){
		$http.get(webServiceUrl+'discounts')
		.success(function(response) {				
			var data=response.result;
			if(response.value!=0){
				$.each(data, function (index,Object) {
					var pdetails=Object.prescription_details;
					var details=pdetails.split('**');
					if(details.length>0){
						for(var i=0;i<1;i++){
							if(typeof details[i]!='undefined'){
								var names=details[i].split('$$');
								data[index].Tabletname=names[0];
								data[index].Quantity=names[1];
								data[index].preLength=details.length;
							}
						}
					}
				});				
				$scope.tableParams = new ngTableParams({
					page: 1,            // show first page
					count: 10           // count per page
				}, {
					total: data.length, // length of data
					getData: function($defer, params) {
						$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
					}
				});	
			}else{
				$scope.errornodata_message=errornodata_message;
			}	
		});
	}else{
		location.href="#";
	}
});
mcAdminApp.controller('allUsers', function($scope,$sce,$http,ngTableParams,ngDialog,$compile) {
	$scope.allDetails		=	$sce.trustAsHtml('');
	$scope.index = 0;
	$scope.errornodata_message="";
	$scope.changeStatus = function(status,u_id,u_type_id){
		var Ctype="";
		if(status==0){
			Ctype="Block";
		}else{
			Ctype="Active";
		}
		var dataObj = {
			status			:	status,	
			compliantType	:	Ctype,
			user_type_id	:	u_type_id,
			tracking_id  	:	0,
			complaint_id  	:	0	
		};
		$http.put(webServiceUrl+'admin-delete-user/'+u_id,dataObj)
		.success(function(data) {
			if(data.output=="success")
			{
				if(data.status==0)
				{
					var acHtml="<a  href='javascript:void(0);' ng-click='changeStatus(1,"+u_id+","+u_type_id+")' href='javascript:void(0)'>Active/</a>";
					var emt = $compile(acHtml)($scope);
					$('#b'+u_id).html('');
					$('#b'+u_id).append(emt);
					$('#st'+u_id).html('');
					$('#st'+u_id).append('Blocked');
				}else if(data.status==1){
					var acHtml="<a  href='javascript:void(0);' ng-click='changeStatus(0,"+u_id+","+u_type_id+")' href='javascript:void(0)'>Block/</a>";
					var emt = $compile(acHtml)($scope);
					$('#b'+u_id).html('');
					$('#b'+u_id).append(emt);
					$('#st'+u_id).html('');
					$('#st'+u_id).append('Active');
				 }
			}
			
		});
	};
	$scope.openPopups = function(type,user_m_id) {
	$http.get(webServiceUrl+'register/'+user_m_id)
		.success(function(response) {
			var viewDetailes="";
			var pdata=response.data;
			var status='';
			console.log(pdata);
			if(pdata.status=1){
				status='Active';
			}else if(pdata.status=0){
				status='Blocked';
			}
			viewDetailes+='<tr><th>User Name</th><th>'+pdata.user_name+'</th></tr>'+
			'<tr><th>Email</th><th>'+pdata.email+'</th></tr>'+
			'<tr><th>Landmark</th><th>'+pdata.landmark+'</th></tr>'+
			'<tr><th>Address</th><th>'+pdata.address+'</th></tr>'+
			'<tr><th>Phone Number</th><th>'+pdata.phone+'</th></tr>'+
			'<tr><th>Alter Phonenumber</th><th>'+pdata.alterphone+'</th></tr>'+
			'<tr><th>Location</th><th>'+pdata.location+'</th></tr>'+
			'<tr><th>Pincode</th><th>'+pdata.pincode+'</th></tr>'+
			'<tr><th>Status</th><th>'+status+'</th></tr>';			
			$scope.allDetails		=	$sce.trustAsHtml(viewDetailes);
			 if(type==2){
				var openPopupId="viewDetails.html";
			}
			ngDialog.open({
				template: openPopupId,
				className: 'ngdialog-theme-plain',
				scope:$scope
			});
		});
	}	
	if(typeof sessionStorage["admin_user_id"]!=undefined){
		var dataObj = {
			type_id			:	'2',
			status			:	'1'
		};	
		$http.post(webServiceUrl+'admin-all-shops',dataObj)
		.success(function(response) {
			if(response.value!=0){
				var data=response.shopData;
				$scope.tableParams = new ngTableParams({
					page: 1,            // show first page
					count: 10           // count per page
				}, {
					total: data.length, // length of data
					getData: function($defer, params) {
						$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
					}
				});
			}else{
					$scope.errornodata_message=errornodata_message;
			}			
		});
	}else{
		location.href="#";
	}
});
mcAdminApp.controller('newOrdersController', function($scope,$sce,$http,ngTableParams,ngDialog,$compile) {
	$scope.allPriscription		=	$sce.trustAsHtml('');
	$scope.allDetails			=	$sce.trustAsHtml('');
	$scope.ShopDetailes			=	$sce.trustAsHtml('');
	$scope.index = 0;
	//Cancel Order
	$scope.cancelOrder = function(tracking_id){
		var Cancelledorder_tracking_id=tracking_id;
		var dataObj = {
			compliantType			:	'Cancelled',
			complaint_id			:	0,
			tracking_id         	:	Cancelledorder_tracking_id
		};	
		$http.put(webServiceUrl+'order/'+Cancelledorder_tracking_id,dataObj)
		.success(function(data) {
			if(data.value==1){
				var stEmt = '<a href="javascript:void(0)" ng-click="openPopups(2,'+tracking_id+')">View</a>';
				var emt = $compile(stEmt)($scope);
				$('#st'+tracking_id).html('');
				$('#st'+tracking_id).append('Cancelled');
				$('#ac'+tracking_id).html('');
				$('#ac'+tracking_id).append(emt);				
			}
		});
	}
	// Send Quotation
	$scope.popupopensendQuotation=function(type,pincode,tracking_id,location){
	if(type==4){
		var openSendQuotationPopup="viewsendquotation.html";
	}
	ngDialog.open({
		template: openSendQuotationPopup,
		className: 'ngdialog-theme-plain',
		scope:$scope
	});
	//var location=$('#location'+tracking_id).val();
	var htmlSendQuotationPopup="";
	    var dataObj = {
			pincode		:	pincode,
			location	:	location,
			type_id		:	3,
			status		:	1
		};	
		$http.post(webServiceUrl+'admin-all-shops',dataObj)
		.success(function(data){
			if(data.value==1){
				htmlSendQuotationPopup+='<form id="discounttForm"><p>Tracking Id:'+tracking_id+'</p>';
				htmlSendQuotationPopup+='<table><tr>'+
				'<td>Location:</td><td>'+location+'</td>'+
				'<td>Pincode:</td><td>'+pincode+'</td>'+
				'</tr></table>';
				htmlSendQuotationPopup+='<table class="table table-bordered">'+
							'<tr class="table_th_bg">'+
							'<th><input type="checkbox" id="allCheck" name="allCheck" ng-click="selectAllCheck()">SelectAll</th>'+
							'<th>Shop Name</th>'+
							'<th>Contact Number</th>'+
							'<th>Alternative Number</th>'+
						'</tr>';
						
				var obj = data.shopData;
				$.each(obj, function (index,Object) {
					htmlSendQuotationPopup+=	'<tr>'+
								'<td><input type="checkbox" class="Check1" name="Check[]" ng-click="uncheckSelectAll()" value="'+Object.user_id+'"></td>'+
								'<td>'+Object.user_name+'</td>'+
								'<td>'+Object.phone+'</td>'+
								'<td>'+Object.alterphone+'</td>'+
							'</tr>';
				});
				htmlSendQuotationPopup+='</table>'+
				'<div class="control-group">'+
					'<label class="control-label" for="inputAd">Discount</label>'+
					'<div class="controls">'+
						'<input type="radio" id="discountt1" name="discountt" ng-click="discountSelect(1)"> Yes &nbsp;&nbsp;'+
						'<input type="radio" id="discountt0" name="discountt" ng-click="discountSelect(0)" checked> No'+
					'</div>'+
				'</div>'+
				'<div class="control-group" style="display:none" id="PriceRadio">'+
						'<label class="control-label" for="phone">Price</label>'+
						'<div class="controls">'+
						'<input type="text" class="span4" id="Price" name="Price">'+
						'<span id="PriceError" style="color:red"></span>'+
						'</div>'+
					'</div><p><a href="javascript:void(0);" ng-click="sendQuotationToShops('+tracking_id+');">Send</a></p></form>'+
					'<span id="checkboxError" style="color:red"></span>'+
					'<span id="sendsuccess" style="color:green"></span>'+
					'<input type="hidden" id="hidDiscountValue" name="hidDiscountValue" value="0"/>';
					//$scope.ShopDetailes			=	$sce.trustAsHtml(htmlSendQuotationPopup);
					var Popup = $compile(htmlSendQuotationPopup)($scope);
					$('#shopdetailes').append(Popup);
			}
		});
	}
	$scope.sendQuotationToShops=function(tracking_id){
		var admin_id = JSON.parse(sessionStorage["admin_user_id"]);
		$('#sendsuccess').html('');
		var flag=true;
		var selectedShops="";
		var checkboxes=document.getElementsByTagName("INPUT");	
		var len=checkboxes.length;	
		var cnt = 0;
		for(var i=0;i<len;i++)
		{		
			if(checkboxes[i].name=="Check[]")
			{		
				if(checkboxes[i].checked)
				{
					selectedShops+=checkboxes[i].value+'***';
					cnt++;
				}
			}
		}
		if(cnt == 0) 
		{
			$('#checkboxError').html(Select_shops_send_quotation);
			flag=false;
		}else{
			$('#checkboxError').html('');
		}
		if($('#hidDiscountValue').val()==1){
			if($('#Price').val()==""){
				$('#PriceError').html(send_price);
				flag=false;
			}else if(isNaN($('#Price').val())){
				$("#PriceError").html(send_numbers_message);
				flag=false;
			}else{
				var discount=$('#Price').val();
				 $('#PriceError').html('');
			}
		}else{
			$('#Price').val("");
			var discount=$('#Price').val();
		}
		
		if(flag==true){
			var shops=selectedShops.slice(0,-3);
			var dataObj = {
				shop_ids:shops,
				user_medicine_order_id:tracking_id,
				discount:discount,
				compliantType:"sendQuotation",
				user_id:"0",
				complaint_id:"0",
				tracking_id:tracking_id
			};	
			$http.post(webServiceUrl+'send-notification-to-shops',dataObj)
				.success(function(data){
				if(data.value==1){
						$('#sendsuccess').html(Quotation_sent_successfully_message);
						$('#status'+tracking_id).html(Quotation_send);
						$('#SendQuotation'+tracking_id).html(Resend_quotation);
				}
			});
		}
	}
	$scope.discountSelect=function(num){
		if(num==1){
			$('#PriceRadio').show();
		}else{
			$('#PriceRadio').hide();
		}
			$('#hidDiscountValue').val(num);
	}
	$scope.uncheckSelectAll=function(){
		var flag=true;
		var checkboxes=document.getElementsByTagName("INPUT");	
		var len=checkboxes.length;	
		var cnt = 0;
		for(var i=0;i<len;i++)
		{		
			if(checkboxes[i].name=="Check[]")
			{		
				if(checkboxes[i].checked==false)
				{
					$('#allCheck').prop('checked',false); 
					flag=false;
				}
			}
		}
		if(flag==true){
			$('#allCheck').prop('checked',true); 
		}
	}
	$scope.selectAllCheck=function(){
		if($('#allCheck').prop('checked')) { 
			$('.Check1').prop('checked',true);
		}else{
			$('.Check1').prop('checked',false);                     
		}
	}

	//End 
	$scope.openPopups = function(type,user_m_id) {
	$http.get(webServiceUrl+'getprescription/'+user_m_id+'-0')
		.success(function(response) {
			var viewDetailes="";
			var viewallImages=[];
			var pdata=response.result;
			var viewAll='<tr><th>Tablet name</th><th>Quantity</th></tr>';
			$.each(pdata, function (index,Object) {
				//All Tabletes Pop up
				var prdetails=Object.prescription_details;
				var detailss=prdetails.split('**');
				if(detailss.length>0){
					for(var i=0;i<=(detailss.length-1);i++){
						var namess=detailss[i].split('$$');
						viewAll+='<tr><th>'+namess[0]+'</th>'+'<th>'+namess[1]+'</th></tr>';
					}
				}
				//End
				//All Order Details Pop Up
				if(Object.auto_renewal==0 || Object.auto_renewal==null){
					var auto_renewal='No';
				}else{
					var auto_renewal='Yes';
				}
				if(Object.each_days==0 || Object.auto_renewal==null){
					var each_days='No';
				}else{
					var each_days=Object.each_days;
				}
				if(Object.delivered_date=="" || Object.delivered_date==null){
					var deliverdDate="Not delivered";
				}else{
					var deliverdDate=Object.delivered_date;
				}
				if(Object.immediate==0 || Object.immediate==null){
					var immidiate='Not Immidiate';
				}else{
					var immidiate='Yes';
				}
				if(Object.availabletime==0 || Object.availabletime==null){
					var availabletime='Not Mention';
				}else{
					var availabletime=Object.availabletime;
				}
				viewDetailes+='<tr><th>Tracking Id</th><th>'+Object.user_medicine_order_id+'</th></tr>'+
					'<tr><th>Auto renewal </th><th>'+auto_renewal+'</th></tr>'+
					'<tr><th>Days</th><th>'+each_days+'</th></tr>'+
					'<tr><th>Delivered date</th><th>'+deliverdDate+'</th></tr>'+
					'<tr><th>Landmark </th><th>'+Object.landmark+'</th></tr>'+
					'<tr><th>Phone number </th><th>'+Object.phone+'</th></tr>'+
					'<tr><th>Alternative phone number</th><th>'+Object.alterphone+'</th></tr>'+
					'<tr><th>Address</th><th>'+Object.address+'</th></tr>'+
					'<tr><th>Immidiate</th><th>'+immidiate+'</th></tr>'+
					'<tr><th>Available time</th><th>'+availabletime+'</th></tr>';
				//End
				//All Prescription Images Pop Up
					var imagesss=Object.prescription_upload_path;
					var imagespre=imagesss.split('**');
					if(imagespre.length>0){
						for(var img=0;img<=(imagespre.length)-1;img++){
							viewallImages[img]=uploadImgUrl+imagespre[img];
						}
					}
				//End
			});
			$scope.allPriscription		=	$sce.trustAsHtml(viewAll);
			$scope.allDetails		=	$sce.trustAsHtml(viewDetailes);
			$scope.images = viewallImages;
			if(type==1){
				var openPopupId="viewPriscription.html";
			}else if(type==2){
				var openPopupId="viewDetails.html";
			}else if(type==3){
				var openPopupId="viewAllPreImages.html";
			}
			ngDialog.open({
				template: openPopupId,
				className: 'ngdialog-theme-plain',
				scope:$scope
			});
		});
	}
	$scope.updateTsPrevious = function() {
		$scope.tsPrevious = +new Date();
	}
	$scope.updateTsNext = function() {
		$scope.tsNext = +new Date();
	}
	if(typeof sessionStorage["admin_user_id"]!='undefined'){
		var orderhistory='0';
		var viewAll='';
		$http.get(webServiceUrl+'admin-allorders/'+orderhistory)
		.success(function(response) {
			if(response.value==1){
				var data=response.result;
				$.each(data, function (index,Object) {
					if(Object.prescription_upload_path!=""){
						var imagess=Object.prescription_upload_path;
						var images=imagess.split('**');
						data[index].preImageLength=images.length;
						if(images.length>0){
						  for(var i=0;i<1;i++){
							   if(images[i]!=null){
									data[index].preImage=uploadImgUrl+images[i];
								}else{
									data[index].preImage=uploadImgUrl+'default.jpg';
								}
							}
						}
					}else{
						data[index].preImage=uploadImgUrl+'default.jpg';
					}
					var pdetails=Object.prescription_details;
					var details=pdetails.split('**');
					if(details.length>0){
						for(var i=0;i<1;i++){
							if(typeof details[i]!='undefined'){
								var names=details[i].split('$$');
								data[index].Tabletname=names[0];
								data[index].Quantity=names[1];
								data[index].preLength=details.length;
							}
						}
					}
				});	
				$scope.tableParams = new ngTableParams({
					page: 1,            // show first page
					count: 10           // count per page
				}, {
					total: data.length, // length of data
					getData: function($defer, params) {
						$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
					}
				});
			}else{
				var admin_user_id = JSON.parse(sessionStorage["admin_user_id"]);
				$scope.getNotifications(admin_user_id);
				$scope.emptyOrders=errornodata_message;
			}
		});
	}else{
		location.href="#";
	}
});
mcAdminApp.controller('quotationSentOrders', function($scope,$sce,$http,ngTableParams,ngDialog,$compile) {
	$scope.hidDeleteId=false;
	$scope.allPriscription		=	$sce.trustAsHtml('');
	$scope.allDetails			=	$sce.trustAsHtml('');
	$scope.ConfirmDetails		=	$sce.trustAsHtml('');
	$scope.index = 0;
	$scope.cancelOrder = function(tracking_id){
		var Cancelledorder_tracking_id=tracking_id;
		var dataObj = {
			compliantType			:	'Cancelled',
			complaint_id			:	0,
			tracking_id         	:	Cancelledorder_tracking_id
		};	
		$http.put(webServiceUrl+'order/'+Cancelledorder_tracking_id,dataObj)
		.success(function(data) {
			if(data.value==1){
				var stEmt = '<a href="javascript:void(0)" ng-click="openPopups(2,'+tracking_id+')">View</a>';
				var emt = $compile(stEmt)($scope);
				$('#st'+tracking_id).html('');
				$('#st'+tracking_id).append('Cancelled');
				$('#ac'+tracking_id).html('');
				$('#ac'+tracking_id).append(emt);				
			}
		});
	}
	//Confirm Shop Popup
	$scope.openPopupConfirm = function(type,tracking_id) {
	//var location=$('#location'+tracking_id).val();
		var htmlPopup="";
		if(type==1){
			var openPopupId="viewConfirmShop.html";
		}
		ngDialog.open({
			template: openPopupId,
			className: 'ngdialog-theme-plain',
			scope:$scope
		});
		$http.get(webServiceUrl+'confirm-shop-pop-up/'+tracking_id)
		.success(function(data){
			if(data.value==1){
				htmlPopup+='<form id="confirmForm"><p><b>Tracking Id:'+tracking_id+'</b>&nbsp;&nbsp;&nbsp;&nbsp;<span style="color:green" id="successConfirm"><span></p>';
				htmlPopup+='<table class="table table-bordered">'+
							'<tr class="table_th_bg">'+
							'<th>Time</th>'+
							'<th>Shop Name</th>'+
							'<th>Price</th>'+
							'<th>Contact Number</th>'+
							'<th>Alternative Number</th>'+
							'<th>Action</th>'+
						'</tr>';
				var obj = eval("(" + data.orders + ")");
				var deletIds="";
				$.each(obj, function (index,Object) {
					htmlPopup+=	'<tr>'+
					'<td>'+Object.date_updated+'</td>'+
					'<td>'+Object.user_name+'</td>';
					if(Object.price!=null){
						htmlPopup+=	'<td>'+Object.price+'</td>';
					}else{
						htmlPopup+=	'<td>Not sent</td>';
					}
					htmlPopup+=	'<td>'+Object.phone+'</td>'+
					'<td>'+Object.alterphone+'</td>';
					if(Object.price!=null){
						if(Object.shop_order_status==2){
							htmlPopup+=	'<td id="confirmm'+Object.order_delivery_details_id+'"><b style="color:red">Confirm</b></td>';
						}else if(Object.shop_order_status==3){
							htmlPopup+=	'<td id="confirmm'+Object.order_delivery_details_id+'"><a href="javascript:void(0);" ng-click="confirmOrder('+Object.order_delivery_details_id+','+tracking_id+')"><b style="color:green">Confirm</b></a></td>';
						}else if(Object.shop_order_status==1){
							htmlPopup+=	'<td id="confirmm'+Object.order_delivery_details_id+'"><a href="javascript:void(0);" ng-click="confirmOrder('+Object.order_delivery_details_id+','+tracking_id+')"><b style="color:green">Confirm</b></a></td>';
						}else if(Object.shop_order_status==0){
							htmlPopup+=	'<td id="confirmm'+Object.order_delivery_details_id+'"><a href="javascript:void(0);" ng-click="confirmOrder('+Object.order_delivery_details_id+')"><b style="color:green">Confirm</b></a></td>';
						}
					}else{
						htmlPopup+=	'<td id="confirmm'+Object.order_delivery_details_id+'">Not Sent</td>';
					}
				'</tr>';
						deletIds+=Object.order_delivery_details_id+'***';
				});
				htmlPopup+='</table></form>';
				var hidDeleteHtml='<input type="text" id="deleteIds" name="deleteIds" value="'+deletIds+'" ng-model="quotation.deleteIds"  ng-init="quotation.deleteIds='+deletIds+'" />';
				$('#hidDelete').html('');
				$('#hidDelete').append(hidDeleteHtml);
				//open popup start
				var Popup = $compile(htmlPopup)($scope);
				$('#ConfirmDetails').append(Popup);
				//$scope.ConfirmDetails		=	$sce.trustAsHtml(htmlPopup);
				//End
			}
		});
	}
	//Confirm shop
	$scope.confirmOrder=function(oddId,trackingId){
		var admin_id = JSON.parse(sessionStorage["admin_user_id"]);
		var delOrderIds=$('#deleteIds').val().slice(0,-3);
		dataObj={
			admin_confirm			:	1,
			status					:	1,
			confirmOrderId			:	oddId,
			deleteOrderids			:	delOrderIds,
			admin_id				:	admin_id,
			complaintType			:	"Confirmed",
			trackingId				:	trackingId
		}
		$http.put(webServiceUrl+'order-quotations-from-shops/1',dataObj)
			.success(function(response){
				if(response.value==1){
					$('#successConfirm').html('Confirm Shop Success');
					var ids=delOrderIds.split('***');
					for(var i=0;i<=(ids.length-1);i++){
						if(ids[i]!=oddId){
							$('#confirmm'+ids[i]).html('<b style="color:red">Canceled</b>');
						}else{
							$('#confirmm'+ids[i]).html('<b style="color:green">Confirmed</b>');
						}
					}
				}
			});
	}
	$scope.openPopups = function(type,user_m_id) {
	$http.get(webServiceUrl+'getprescription/'+user_m_id+'-0')
		.success(function(response) {
			var viewDetailes="";
			var viewallImages=[];
			var pdata=response.result;
			var viewAll='<tr><th>Tablet name</th><th>Quantity</th></tr>';
			$.each(pdata, function (index,Object) {
				//All Tabletes Pop up
				var prdetails=Object.prescription_details;
				var detailss=prdetails.split('**');
				if(detailss.length>0){
					for(var i=0;i<=(detailss.length-1);i++){
						var namess=detailss[i].split('$$');
						viewAll+='<tr><th>'+namess[0]+'</th>'+'<th>'+namess[1]+'</th></tr>';
					}
				}
				//End
				//All Order Details Pop Up
				if(Object.auto_renewal==0 || Object.auto_renewal==null){
					var auto_renewal='No';
				}else{
					var auto_renewal='Yes';
				}
				if(Object.each_days==0 || Object.auto_renewal==null){
					var each_days='No';
				}else{
					var each_days=Object.each_days;
				}
				if(Object.delivered_date=="" || Object.delivered_date==null){
					var deliverdDate="Not delivered";
				}else{
					var deliverdDate=Object.delivered_date;
				}
				if(Object.immediate==0 || Object.immediate==null){
					var immidiate='Not Immidiate';
				}else{
					var immidiate='Yes';
				}
				if(Object.availabletime==0 || Object.availabletime==null){
					var availabletime='Not Mention';
				}else{
					var availabletime=Object.availabletime;
				}
				viewDetailes+='<tr><th>Tracking Id</th><th>'+Object.user_medicine_order_id+'</th></tr>'+
					'<tr><th>Auto renewal </th><th>'+auto_renewal+'</th></tr>'+
					'<tr><th>Days</th><th>'+each_days+'</th></tr>'+
					'<tr><th>Delivered date</th><th>'+deliverdDate+'</th></tr>'+
					'<tr><th>Landmark </th><th>'+Object.landmark+'</th></tr>'+
					'<tr><th>Phone number </th><th>'+Object.phone+'</th></tr>'+
					'<tr><th>Alternative phone number</th><th>'+Object.alterphone+'</th></tr>'+
					'<tr><th>Address</th><th>'+Object.address+'</th></tr>'+
					'<tr><th>Immidiate</th><th>'+immidiate+'</th></tr>'+
					'<tr><th>Available time</th><th>'+availabletime+'</th></tr>';
				//End
				//All Prescription Images Pop Up
					var imagesss=Object.prescription_upload_path;
					var imagespre=imagesss.split('**');
					if(imagespre.length>0){
						for(var img=0;img<=(imagespre.length)-1;img++){
							viewallImages[img]=uploadImgUrl+imagespre[img];
						}
					}
				//End
			});
			$scope.allPriscription		=	$sce.trustAsHtml(viewAll);
			$scope.allDetails		=	$sce.trustAsHtml(viewDetailes);
			$scope.images = viewallImages;
			if(type==1){
				var openPopupId="viewPriscription.html";
			}else if(type==2){
				var openPopupId="viewDetails.html";
			}else if(type==3){
				var openPopupId="viewAllPreImages.html";
			}
			ngDialog.open({
				template: openPopupId,
				className: 'ngdialog-theme-plain',
				scope:$scope
			});
		});
	}
	$scope.updateTsPrevious = function() {
		$scope.tsPrevious = +new Date();
	}
	$scope.updateTsNext = function() {
		$scope.tsNext = +new Date();
	}
	if(typeof sessionStorage["admin_user_id"]!='undefined'){
		var orderhistory='1';
		var viewAll='';
		$http.get(webServiceUrl+'admin-allorders/'+orderhistory)
		.success(function(response) {
			if(response.value==1){
				var data=response.result;
				$.each(data, function (index,Object) {
					if(Object.prescription_upload_path!=""){
						var imagess=Object.prescription_upload_path;
						var images=imagess.split('**');
						data[index].preImageLength=images.length;
						if(images.length>0){
						  for(var i=0;i<1;i++){
							   if(images[i]!=null){
									data[index].preImage=uploadImgUrl+images[i];
								}else{
									data[index].preImage=uploadImgUrl+'default.jpg';
								}
							}
						}
					}else{
						data[index].preImage=uploadImgUrl+'default.jpg';
					}
					var pdetails=Object.prescription_details;
					var details=pdetails.split('**');
					if(details.length>0){
						for(var i=0;i<1;i++){
							if(typeof details[i]!='undefined'){
								var names=details[i].split('$$');
								data[index].Tabletname=names[0];
								data[index].Quantity=names[1];
								data[index].preLength=details.length;
							}
						}
					}
				});	
				$scope.tableParams = new ngTableParams({
					page: 1,            // show first page
					count: 10           // count per page
				}, {
					total: data.length, // length of data
					getData: function($defer, params) {
						$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
					}
				});
			}else{
				var admin_user_id = JSON.parse(sessionStorage["admin_user_id"]);
				$scope.getNotifications(admin_user_id);
				$scope.emptyOrders=errornodata_message;
			}
		});
	}else{
		location.href="#";
	}
});
mcAdminApp.controller('orderHistoryController', function($scope,$sce,$http,ngTableParams,ngDialog,$compile) {
	$scope.allPriscription		=	$sce.trustAsHtml('');
	$scope.allDetails		=	$sce.trustAsHtml('');
	$scope.index = 0;
	$scope.cancelOrder = function(tracking_id){
		var Cancelledorder_tracking_id=tracking_id;
		var dataObj = {
			compliantType			:	'Cancelled',
			complaint_id			:	0,
			tracking_id         	:	Cancelledorder_tracking_id
		};	
		$http.put(webServiceUrl+'order/'+Cancelledorder_tracking_id,dataObj)
		.success(function(data) {
			if(data.value==1){
				var stEmt = '<a href="javascript:void(0)" ng-click="openPopups(2,'+tracking_id+')">View</a>';
				var emt = $compile(stEmt)($scope);
				$('#st'+tracking_id).html('');
				$('#st'+tracking_id).append('Cancelled');
				$('#ac'+tracking_id).html('');
				$('#ac'+tracking_id).append(emt);				
			}
		});
	}
	$scope.openPopups = function(type,user_m_id) {
	$http.get(webServiceUrl+'getprescription/'+user_m_id+'-0')
		.success(function(response) {
			var viewDetailes="";
			var viewallImages=[];
			var pdata=response.result;
			var viewAll='<tr><th>Tablet name</th><th>Quantity</th></tr>';
			$.each(pdata, function (index,Object) {
				//All Tabletes Pop up
				var prdetails=Object.prescription_details;
				var detailss=prdetails.split('**');
				if(detailss.length>0){
					for(var i=0;i<=(detailss.length-1);i++){
						var namess=detailss[i].split('$$');
						viewAll+='<tr><th>'+namess[0]+'</th>'+'<th>'+namess[1]+'</th></tr>';
					}
				}
				//End
				//All Order Details Pop Up
				if(Object.auto_renewal==0 || Object.auto_renewal==null){
					var auto_renewal='No';
				}else{
					var auto_renewal='Yes';
				}
				if(Object.each_days==0 || Object.auto_renewal==null){
					var each_days='No';
				}else{
					var each_days=Object.each_days;
				}
				if(Object.delivered_date=="" || Object.delivered_date==null){
					var deliverdDate="Not delivered";
				}else{
					var deliverdDate=Object.delivered_date;
				}
				if(Object.immediate==0 || Object.immediate==null){
					var immidiate='Not Immidiate';
				}else{
					var immidiate='Yes';
				}
				if(Object.availabletime==0 || Object.availabletime==null){
					var availabletime='Not Mention';
				}else{
					var availabletime=Object.availabletime;
				}
				viewDetailes+='<tr><th>Tracking Id</th><th>'+Object.user_medicine_order_id+'</th></tr>'+
					'<tr><th>Auto renewal </th><th>'+auto_renewal+'</th></tr>'+
					'<tr><th>Days</th><th>'+each_days+'</th></tr>'+
					'<tr><th>Delivered date</th><th>'+deliverdDate+'</th></tr>'+
					'<tr><th>Landmark </th><th>'+Object.landmark+'</th></tr>'+
					'<tr><th>Phone number </th><th>'+Object.phone+'</th></tr>'+
					'<tr><th>Alternative phone number</th><th>'+Object.alterphone+'</th></tr>'+
					'<tr><th>Address</th><th>'+Object.address+'</th></tr>'+
					'<tr><th>Immidiate</th><th>'+immidiate+'</th></tr>'+
					'<tr><th>Available time</th><th>'+availabletime+'</th></tr>';
				//End
				//All Prescription Images Pop Up
					var imagesss=Object.prescription_upload_path;
					var imagespre=imagesss.split('**');
					if(imagespre.length>0){
						for(var img=0;img<=(imagespre.length)-1;img++){
							viewallImages[img]=uploadImgUrl+imagespre[img];
						}
					}
				//End
			});
			$scope.allPriscription		=	$sce.trustAsHtml(viewAll);
			$scope.allDetails		=	$sce.trustAsHtml(viewDetailes);
			$scope.images = viewallImages;
			if(type==1){
				var openPopupId="viewPriscription.html";
			}else if(type==2){
				var openPopupId="viewDetails.html";
			}else if(type==3){
				var openPopupId="viewAllPreImages.html";
			}
			ngDialog.open({
				template: openPopupId,
				className: 'ngdialog-theme-plain',
				scope:$scope
			});
		});
	}
	$scope.updateTsPrevious = function() {
		$scope.tsPrevious = +new Date();
	}
	$scope.updateTsNext = function() {
		$scope.tsNext = +new Date();
	}
	if(typeof sessionStorage["admin_user_id"]!='undefined'){
		var orderhistory='all';
		var viewAll='';
		$http.get(webServiceUrl+'admin-allorders/'+orderhistory)
		.success(function(response) {
			if(response.value==1){
				var data=response.result;
				$.each(data, function (index,Object) {
					if(Object.prescription_upload_path!=""){
						var imagess=Object.prescription_upload_path;
						var images=imagess.split('**');
						data[index].preImageLength=images.length;
						if(images.length>0){
						  for(var i=0;i<1;i++){
							   if(images[i]!=null){
									data[index].preImage=uploadImgUrl+images[i];
								}else{
									data[index].preImage=uploadImgUrl+'default.jpg';
								}
							}
						}
					}else{
						data[index].preImage=uploadImgUrl+'default.jpg';
					}
					var pdetails=Object.prescription_details;
					var details=pdetails.split('**');
					if(details.length>0){
						for(var i=0;i<1;i++){
							if(typeof details[i]!='undefined'){
								var names=details[i].split('$$');
								data[index].Tabletname=names[0];
								data[index].Quantity=names[1];
								data[index].preLength=details.length;
							}
						}
					}
				});	
				$scope.tableParams = new ngTableParams({
					page: 1,            // show first page
					count: 10           // count per page
				}, {
					total: data.length, // length of data
					getData: function($defer, params) {
						$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
					}
				});
			}else{
				var admin_user_id = JSON.parse(sessionStorage["admin_user_id"]);
				$scope.getNotifications(admin_user_id);
				$scope.emptyOrders=errornodata_message;
			}
		});
	}else{
		location.href="#";
	}
});
mcAdminApp.factory( 'adminConrolUsersService',function()
{
	var adminFactory = {};
	
	adminFactory.changeStatus = function( status,user_id,user_type_id )
	{
		var Ctype="";
		if(status==0){
			Ctype="Block";
		}else{
			Ctype="Active";
		}
		$.ajax({
			type		:	'PUT',
			url			:  	 webServiceUrl+'admin-delete-user/'+user_id,
			data 		: {status:status,compliantType:Ctype,user_type_id:user_type_id,tracking_id:'0',complaint_id:'0'},
			dataType	: 	"json",
			success: function(data){
				if(data.output=="success")
				{
					if(status=='0')
					{
						$('#status'+user_id).html('Blocked');
						$('#userpopup'+user_id).html('Blocked');
						$('#user'+user_id).html('<a href="javascript:void(0);" onclick="changeStatus(1,'+user_id+','+user_type_id+')">Active</a>'+'/'+'<a href="#view'+user_id+'" role="button" class="" data-toggle="modal">View</a>');
					}
					 else{
						$('#status'+user_id).html('Active');
						$('#userpopup'+user_id).html('Active');
						$('#user'+user_id).html('<a  href="javascript:void(0);" onclick="changeStatus(0,'+user_id+',,'+user_type_id+')">Block</a>'+'/'+'<a href="#view'+user_id+'" role="button" class="" data-toggle="modal">View</a>');
					 }
				}
			}
		});
	}
	
	return adminFactory;
});

mcAdminApp.controller('adminLoginController', function($scope,$sce,$http) {
	var self = this;
	$scope.setActivePage = function(name) {
      if(typeof sessionStorage["admin_user_id"]!='undefined'){
		$scope.user_id 		= 	JSON.parse(sessionStorage["admin_user_id"]);
		$scope.email 		= 	JSON.parse(sessionStorage["admin_email"]);
		$scope.phone 		= 	JSON.parse(sessionStorage["admin_phone"]);
		$scope.location 	=	JSON.parse(sessionStorage["admin_location"]);
		$scope.headding		=	$sce.trustAsHtml('<div class="text_l top_strip_left_text"><span id="updateLocation" name="updateLocation" >'+$scope.location+'</span><span id="updatePhone" name="updatePhone" >Ph:&nbsp;'+$scope.phone+'</span><span>Email:&nbsp;'+$scope.email+'</div><div class="text_r top_strip_right_text"><span>Welcome to medicart</span><span id="myaccounthid"><a href="#account">My Account</a></span><span id="loginLogout"><a href="#logout">Logout</a></span></div>');
		//window.location='#/account';
		}else{
			$scope.headding		=	$sce.trustAsHtml('<div id="headding" class="row_text_lr"><div class="text_r top_strip_right_text"><span>Welcome to medicart</span><span id="loginLogout"><a href="#">Login</a></span></div></div>');
			$scope.loading		=	$sce.trustAsHtml('');
			$scope.errorLoginMessage='';
		}
   }
	/*$scope.activeSideMenu = function() {
		$('#menuactive ul li a').each(function(){
			var presentPage=this.href.split('#');
			if($location.path().substring(1)==presentPage[1]){
				$(this).addClass('arrow_left');
			}
		});
	}*/
	$scope.getNotifications = function(userId) {
		$http.get(webServiceUrl+'notifications/'+'1'+'-'+userId)
		.success(function(response) {
			if(response.count!=0){
				$scope.notificationsCount=response.count;
			}else{
				$scope.notificationsCount=0;
			}
		});
	}
	$scope.adminLoginProces = function(adminLoginForm) {
		$scope.loading		=	$sce.trustAsHtml('<img src="images/ajax-loader.gif"/>');
		var dataObj = {
			email			:	adminLoginForm.username.$viewValue,
			pwd				:	adminLoginForm.password.$viewValue,
			user_type_id	:	'1'
		};	
		$http.post(webServiceUrl+'login',dataObj)
			.success(function(response) {
				$scope.loading		=	$sce.trustAsHtml('');
				if( response.UserDetails ){
					$scope.UserDetails=response.UserDetails;
					sessionStorage.setItem( 'admin_user_id', JSON.stringify($scope.UserDetails.user_id) );		
					sessionStorage.setItem( 'admin_email', JSON.stringify($scope.UserDetails.email) );
					sessionStorage.setItem( 'admin_user_name', JSON.stringify($scope.UserDetails.user_name) );
					sessionStorage.setItem( 'admin_phone', JSON.stringify($scope.UserDetails.phone) );
					sessionStorage.setItem( 'admin_location', JSON.stringify($scope.UserDetails.location) );
					window.location="#/account";
				}else{
					$scope.errorLoginMessage=Login_error_message;
				}
			});
	}
	$scope.setActivePage();
});

mcAdminApp.controller('accountController', function($scope,$http,$sce) {
	$scope.p = {};
	$scope.setActivePage();
	if(typeof sessionStorage["admin_user_id"]!='undefined'){
		var user_id = JSON.parse(sessionStorage["admin_user_id"]);
		$scope.posts={};
		 $http.get(webServiceUrl+'registration/'+user_id)
			.success(function(response) {
				$scope.posts = [response.data];
				$scope.getNotifications(user_id);
				//$('#account').addClass('arrow_left');
			});
	}else{
		location.href="#";
	}
	$scope.adminAccountProces = function(adminAccForm) {
		$scope.accloading		=	$sce.trustAsHtml('<img src="images/ajax-loader.gif"/>');
		var admin_user_id = JSON.parse(sessionStorage["admin_user_id"]);
		var adminAccObj=this.p;
		$http.put(webServiceUrl+'registration/'+admin_user_id,adminAccObj)
		.success(function(response) {
			if(response.value=='1'){
				$scope.accloading		='';
				sessionStorage.setItem( 'admin_user_name', JSON.stringify(adminAccObj.user_name) );
				sessionStorage.setItem( 'admin_phone', JSON.stringify(adminAccObj.phone) );
				sessionStorage.setItem( 'admin_location', JSON.stringify(adminAccObj.location) );
				$('#success_alert').show();
				$scope.successDiv		= Account_page_success_message;
				$("html, body").animate({ scrollTop: 0 }, 600);
				$('#success_alert').delay(3000).fadeOut('slow');
				$scope.setActivePage();
			}
		});
	}
});

mcAdminApp.controller('addShopController', function($scope,$http,$sce) {
	$scope.shop = {};
	$scope.setActivePage();
	$scope.addShopProces = function(addShopForm) {
		$scope.addShoploading		=	$sce.trustAsHtml('<img src="images/ajax-loader.gif"/>');
		var shopObj=this.shop;
		if(shopObj.password != shopObj.ConformPassword)
		{
			$scope.addShoploading		=	$sce.trustAsHtml('');
			$scope.errorCPassword	=	Change_errorconfirm_password;
		}
		else
		{
			var dataObj = {
				inputFirstname			:	addShopForm.shopFirstName.$viewValue,
				inputEmail				:	addShopForm.inputEmail.$viewValue,
				inputTelephone			:	addShopForm.inputTelephone.$viewValue,
				alterphone				:	addShopForm.alterphone.$viewValue,
				landmark				:	addShopForm.landmark.$viewValue,
				location				:	addShopForm.shopLocation.$viewValue,
				inputAddress			:	addShopForm.inputAddress.$viewValue,
				pincode					:	addShopForm.pincode.$viewValue,
				password				:	addShopForm.password.$viewValue,
				compliantType			:	'Register',
				tracking_id				:	'0',
				user_id					:	'0',
				complaint_id			:	'0'
			};	
			$http.post(webServiceUrl+'shopregister',dataObj)
			.success(function(response) {
				$scope.addShoploading		=	$sce.trustAsHtml('');
				$scope.errorCPassword	=	'';
				if(response.UserId!='0'){
					var admin_user_id = JSON.parse(sessionStorage["admin_user_id"]);
					$scope.getNotifications(admin_user_id);
					//window.location="#/account";
				}
			});
		}
	}
});

mcAdminApp.controller('fpController', function($scope,$http,$sce) {
	$scope.adminfp = {};
	$scope.setActivePage();
	$scope.adminFpProces = function(adminFpForm) {
	$scope.adminFploading		=	$sce.trustAsHtml('<img src="images/ajax-loader.gif"/>');
		var dataObj = {
			email			:	adminFpForm.inputuser.$viewValue,
			type            : 1
		};	
		$http.post(webServiceUrl+'forgetpassword',dataObj)
		.success(function(response) {
			$scope.adminFploading		=	$sce.trustAsHtml('');
		});
	}
});

mcAdminApp.controller('resetPwdController', function($scope,$http,$sce) {
	$scope.setActivePage();
	//alert("");
	$scope.adminRp = {};
	$scope.adminResetPwdProces = function(adminResetpasswordForm) {
		$scope.adminRpLoading		=	$sce.trustAsHtml('<img src="images/ajax-loader.gif"/>');
		var adminRpObj=this.adminRp;
		if(adminRpObj.adminResetPassword != adminRpObj.Confirmpassword)
		{
			$scope.adminRpLoading		=	$sce.trustAsHtml('');
			$scope.errorCPassword	=	Resetpassword_confirm_errormessage;
		}
		else
		{
			$scope.errorCPassword	=	'';
			var path = window.location.href;
			path = path.replace(/\/$/, "");
			path = decodeURIComponent(path);
			var id=path.split('=');
			var token=id[1];
		   
			var dataObj = {
				cnf_password			:	adminResetpasswordForm.Confirmpassword.$viewValue
			};	
			$http.put(webServiceUrl+'forgetpassword/'+token,dataObj)
			.success(function(response) {
				$scope.adminRpLoading		=	$sce.trustAsHtml('');
				if(response.value==1){
					$('#success_alert').show();
					$('#errorSuccess').html(Resetpassword_success_message);
					$("html, body").animate({ scrollTop: 0 }, 600);
					$('#success_alert').delay(3000).fadeOut('slow');
					$('#error_alert').hide();
				}else{
					$('#errorSuccessError').html(Resetpassword_error_message);
				}
			});
		}
	}
});

mcAdminApp.controller('adminAllShopsController', function($scope,$http,$sce,adminConrolUsersService,ngTableParams,ngDialog,$compile) {
	$scope.allDetails		=	$sce.trustAsHtml('');
	$scope.index = 0;
	$scope.emptyShopsList="";
	$scope.changeStatus = function(status,u_id,u_type_id){
		var Ctype="";
		if(status==0){
			Ctype="Block";
		}else{
			Ctype="Active";
		}
		var dataObj = {
			status			:	status,	
			compliantType	:	Ctype,
			user_type_id	:	u_type_id,
			tracking_id  	:	0,
			complaint_id  	:	0	
		};
		$http.put(webServiceUrl+'admin-delete-user/'+u_id,dataObj)
		.success(function(data) {
			if(data.output=="success")
			{
				if(data.status==0)
				{
					var acHtml="<a  ng-click='changeStatus(1,"+u_id+","+u_type_id+")' href='javascript:void(0)'>Active/</a>";
					var emt = $compile(acHtml)($scope);
					$('#b'+u_id).html('');
					$('#b'+u_id).append(emt);
					$('#st'+u_id).html('');
					$('#st'+u_id).append('Blocked');

				}else if(data.status==1){
					var acHtml="<a  ng-click='changeStatus(0,"+u_id+","+u_type_id+")' href='javascript:void(0)'>Block/</a>";
					var emt = $compile(acHtml)($scope);
					$('#b'+u_id).html('');
					$('#b'+u_id).append(emt);
					$('#st'+u_id).html('');
					$('#st'+u_id).append('Active');
				 }
			}
			
		});
	}
	$scope.openPopups = function(type,user_m_id) {
	$http.get(webServiceUrl+'register/'+user_m_id)
		.success(function(response) {
			var viewDetailes="";
			var pdata=response.data;
			var status='';
			console.log(pdata);
			if(pdata.status=1){
				status='Active';
			}else if(pdata.status=0){
				status='Blocked';
			}
			viewDetailes+='<tr><th>User Name</th><th>'+pdata.user_name+'</th></tr>'+
			'<tr><th>Email</th><th>'+pdata.email+'</th></tr>'+
			'<tr><th>Landmark</th><th>'+pdata.landmark+'</th></tr>'+
			'<tr><th>Address</th><th>'+pdata.address+'</th></tr>'+
			'<tr><th>Phone Number</th><th>'+pdata.phone+'</th></tr>'+
			'<tr><th>Alter Phonenumber</th><th>'+pdata.alterphone+'</th></tr>'+
			'<tr><th>Location</th><th>'+pdata.location+'</th></tr>'+
			'<tr><th>Pincode</th><th>'+pdata.pincode+'</th></tr>'+
			'<tr><th>Status</th><th>'+status+'</th></tr>';			
			$scope.allDetails		=	$sce.trustAsHtml(viewDetailes);
			 if(type==2){
				var openPopupId="viewDetails.html";
			}
			ngDialog.open({
				template: openPopupId,
				className: 'ngdialog-theme-plain',
				scope:$scope
			});
		});
	}	
	if(typeof sessionStorage["admin_user_id"]!=undefined){
		var dataObj = {
			location			:	'',
			pincode				:	'',
			type_id				:	'3',
			status				:	'1'
		};	
		$http.post(webServiceUrl+'admin-all-shops',dataObj)
		.success(function(response) {
			if(response.value!=0){
			var data=response.shopData;
			$scope.tableParams = new ngTableParams({
				page: 1,            // show first page
				count: 10           // count per page
			}, {
				total: data.length, // length of data
				getData: function($defer, params) {
					$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
				}
			});
			}else{ 
				$scope.emptyShopsList=errornodata_message;
			}			
		});
	}else{
		location.href="#";
	}
});

mcAdminApp.controller('adminShopRequestsController', function($scope,$http,$sce,adminConrolUsersService,ngTableParams,ngDialog,$compile) {

	$scope.allDetails		=	$sce.trustAsHtml('');
	$scope.index = 0;
	$scope.emptyShopsList="";
	$scope.changeStatus = function(status,u_id,u_type_id){
		var Ctype="";
		if(status==0){
			Ctype="Block";
		}else{
			Ctype="Active";
		}
		var dataObj = {
			status			:	status,	
			compliantType	:	Ctype,
			user_type_id	:	u_type_id,
			tracking_id  	:	0,
			complaint_id  	:	0	
		};
		$http.put(webServiceUrl+'admin-delete-user/'+u_id,dataObj)
		.success(function(data) {
			if(data.output=="success")
			{
					var emt = '<a  href="javascript:void(0)" ng-click="openPopups(2,'+u_id+')">View</a>';
					var actiS= $compile(emt)($scope);
					$('#ac'+u_id).html('');
					$('#ac'+u_id).append(actiS);
					$('#st'+u_id).html('');
					$('#st'+u_id).append('Activate');
			}			
		});
	};
	$scope.openPopups = function(type,user_m_id) {
	$http.get(webServiceUrl+'register/'+user_m_id)
		.success(function(response) {
			var viewDetailes="";
			var pdata=response.data;
			var status='';
			if(pdata.status==1){
				status='Active';
			}else if(pdata.status==0){
				status='Blocked';
			}else{
				status='Pending';
			}
			viewDetailes+='<tr><th>User Name</th><th>'+pdata.user_name+'</th></tr>'+
			'<tr><th>Email</th><th>'+pdata.email+'</th></tr>'+
			'<tr><th>Landmark</th><th>'+pdata.landmark+'</th></tr>'+
			'<tr><th>Address</th><th>'+pdata.address+'</th></tr>'+
			'<tr><th>Phone Number</th><th>'+pdata.phone+'</th></tr>'+
			'<tr><th>Alter Phonenumber</th><th>'+pdata.alterphone+'</th></tr>'+
			'<tr><th>Location</th><th>'+pdata.location+'</th></tr>'+
			'<tr><th>Pincode</th><th>'+pdata.pincode+'</th></tr>'+
			'<tr><th>Status</th><th>'+status+'</th></tr>';			
			$scope.allDetails		=	$sce.trustAsHtml(viewDetailes);
			if(type==2){
				var openPopupId="viewDetails.html";
			}
			ngDialog.open({
				template: openPopupId,
				className: 'ngdialog-theme-plain',
				scope:$scope
			});
		});
	}	
	if(typeof sessionStorage["admin_user_id"]!=undefined){
		var dataObj = {
			location			:	'',
			pincode				:	'',
			type_id				:	'3',
			status				:	'2'
		};	
		$http.post(webServiceUrl+'admin-all-shops',dataObj)
		.success(function(response) {
			if(response.value!=0){
				var data=response.shopData;
				$scope.tableParams = new ngTableParams({
					page: 1,            // show first page
					count: 10           // count per page
				}, {
					total: data.length, // length of data
					getData: function($defer, params) {
						$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
					}
				});	
			}else{
				$scope.emptyShopsList=errornodata_message;
			}
		});
	}else{
		location.href="#";
	}
});
mcAdminApp.directive('wallopSlider', function () {
    return {
      template: '<div class="wallop-slider {{animationClass}}"><ul class="wallop-slider__list"><li class="wallop-slider__item {{itemClasses[$index]}}" ng-repeat="i in images"><img src="{{i}}"></li></ul><button ng-show="images.length>1" class="st-button wallop-slider__btn wallop-slider__btn--previous btn btn--previous" ng-disabled="prevDisabled" ng-click="onPrevButtonClicked()">Previous</button><button ng-show="images.length>1" class="st-button wallop-slider__btn wallop-slider__btn--next btn btn--next" ng-disabled="nextDisabled" ng-click="onNextButtonClicked()">Next</button></div>',
      restrict: 'EA',
      transclude: true,
      replace: false,
      scope: {
        images: '=',
        animation: '@',
        currentItemIndex: '=',
        onNext: '&',
        onPrevious: '&'
      },
      controller: function($scope, $timeout) {

        $scope.itemClasses = [];

        $scope.$watch('images', function(images) {
          if (images.length) {
            _goTo(0);
          }
        });

        $scope.$watch('itemClasses', function(itemClasses) {
          console.log('itemClasses', itemClasses);
        });

        // set animation class corresponding to animation defined in CSS. e.g. rotate, slide
        if ($scope.animation) {
          $scope.animationClass = 'wallop-slider--' + $scope.animation;
        }

        var _displayOptions = {
          btnPreviousClass: 'wallop-slider__btn--previous',
          btnNextClass: 'wallop-slider__btn--next',
          itemClass: 'wallop-slider__item',
          currentItemClass: 'wallop-slider__item--current',
          showPreviousClass: 'wallop-slider__item--show-previous',
          showNextClass: 'wallop-slider__item--show-next',
          hidePreviousClass: 'wallop-slider__item--hide-previous',
          hideNextClass: 'wallop-slider__item--hide-next'
        };

        function updateClasses() {
          if ($scope.itemClasses.length !== $scope.images.length) {
            $scope.itemClasses = [];
            for (var i=0; i<$scope.images.length; i++) {
              $scope.itemClasses.push('');
            }
          }
        }
        function _nextDisabled() {
          console.log('$scope.currentItemIndex', $scope.currentItemIndex, $scope.images.length);

          return ($scope.currentItemIndex + 1) === $scope.images.length;
        }
        function _prevDisabled() {
          return !$scope.currentItemIndex;
        }
        function _updatePagination() {
          $scope.nextDisabled = _nextDisabled();
          $scope.prevDisabled = _prevDisabled();
        }
        function _clearClasses() {
          for (var i=0; i<$scope.images.length; i++) {
            $scope.itemClasses[i] = '';
          }

        }

        // go to slide
        function _goTo(index) {
          console.log('_goTo', index);
          if (index >= $scope.images.length || index < 0 || index === $scope.currentItemIndex) {

            if (!index) {
              $scope.itemClasses[0] = _displayOptions.currentItemClass;
            }
            return;
          }

          _clearClasses();

          $scope.itemClasses[$scope.currentItemIndex] = (index > $scope.currentItemIndex) ? _displayOptions.hidePreviousClass : _displayOptions.hideNextClass;

          var currentClass = (index > $scope.currentItemIndex) ? _displayOptions.showNextClass : _displayOptions.showPreviousClass;
          $scope.itemClasses[index] = _displayOptions.currentItemClass + ' ' + currentClass;

          $scope.currentItemIndex = index;

          _updatePagination();

        }

        // button event handlers
        // consider using the ng-tap directive to remove delay
        $scope.onPrevButtonClicked = function () {
          _goTo($scope.currentItemIndex - 1);
        };
        $scope.onNextButtonClicked = function () {
          _goTo($scope.currentItemIndex + 1);
        };
        
        $scope.$watch('currentItemIndex', function(newVal, oldVal) {
          if (oldVal > newVal) {
            if (typeof $scope.onPrevious === 'function') {
              $scope.onPrevious();
            }
          } else {
            if (typeof $scope.onNext === 'function') {
              $scope.onNext();
            }
          }
        });

      }
    };
});
mcAdminApp.controller('logoutController', function($scope,$sce) {
	sessionStorage.removeItem("admin_user_id");
	sessionStorage.removeItem("admin_email");
	sessionStorage.removeItem("admin_user_name");
	sessionStorage.removeItem("admin_phone");
	sessionStorage.removeItem("admin_location");
	$scope.setActivePage();
});

//Tomarrow Renewal orderStatusCntrl

mcAdminApp.controller('tommorowRenewalOrdersController', function($scope,$sce,$http,ngTableParams,ngDialog,$compile) {
	$scope.allPriscription		=	$sce.trustAsHtml('');
	$scope.allDetails			=	$sce.trustAsHtml('');
	$scope.index = 0;
	$scope.openPopups = function(type,user_m_id) {
	$http.get(webServiceUrl+'getprescription/'+user_m_id+'-'+'0')
		.success(function(response) {
			var viewDetailes="";
			var viewallImages=[];
			var pdata=response.result;
			var viewAll='<tr><th>Tablet name</th><th>Quantity</th></tr>';
			$.each(pdata, function (index,Object) {
				//All Tabletes Pop up
				var prdetails=Object.prescription_details;
				var detailss=prdetails.split('**');
				if(detailss.length>0){
					for(var i=0;i<=(detailss.length-1);i++){
						var namess=detailss[i].split('$$');
						viewAll+='<tr><th>'+namess[0]+'</th>'+'<th>'+namess[1]+'</th></tr>';
					}
				}
				//End
				//All Order Details Pop Up
				if(Object.auto_renewal==0 || Object.auto_renewal==null){
					var auto_renewal='No';
				}else{
					var auto_renewal='Yes';
				}
				if(Object.each_days==0 || Object.auto_renewal==null){
					var each_days='No';
				}else{
					var each_days=Object.each_days;
				}
				if(Object.delivered_date=="" || Object.delivered_date==null){
					var deliverdDate="Not delivered";
				}else{
					var deliverdDate=Object.delivered_date;
				}
				if(Object.immediate==0 || Object.immediate==null){
					var immidiate='Not Immidiate';
				}else{
					var immidiate='Yes';
				}
				if(Object.availabletime==0 || Object.availabletime==null){
					var availabletime='Not Mention';
				}else{
					var availabletime=Object.availabletime;
				}

				viewDetailes+='<tr><th>Tracking Id</th><th>'+Object.user_medicine_order_id+'</th></tr>'+
					'<tr><th>Auto renewal </th><th>'+auto_renewal+'</th></tr>'+
					'<tr><th>Days</th><th>'+each_days+'</th></tr>'+
					'<tr><th>Delivered date</th><th>'+deliverdDate+'</th></tr>'+
					'<tr><th>Landmark </th><th>'+Object.landmark+'</th></tr>'+
					'<tr><th>Phone number </th><th>'+Object.phone+'</th></tr>'+
					'<tr><th>Alternative phone number</th><th>'+Object.alterphone+'</th></tr>'+
					'<tr><th>Address</th><th>'+Object.address+'</th></tr>'+
					'<tr><th>Immidiate</th><th>'+immidiate+'</th></tr>'+
					'<tr><th>Available time</th><th>'+availabletime+'</th></tr>';
				//End
				//All Prescription Images Pop Up
					var imagesss=Object.prescription_upload_path;
					var imagespre=imagesss.split('**');
					if(imagespre.length>0){
						for(var img=0;img<=(imagespre.length)-1;img++){
							viewallImages[img]=uploadImgUrl+imagespre[img];
						}
					}
				//End
			});
			$scope.allPriscription		=	$sce.trustAsHtml(viewAll);
			$scope.allDetails		=	$sce.trustAsHtml(viewDetailes);
			$scope.images = viewallImages;
			if(type==1){
				var openPopupId="viewPriscription.html";
			}else if(type==2){
				var openPopupId="viewDetails.html";
			}else if(type==3){
				var openPopupId="viewAllPreImages.html";
			}
			ngDialog.open({
				template: openPopupId,
				className: 'ngdialog-theme-plain',
				scope:$scope
			});
		});
	}
	$scope.updateTsPrevious = function() {
		$scope.tsPrevious = +new Date();
	}
	$scope.updateTsNext = function() {
		$scope.tsNext = +new Date();
	}
	// Function sendOrderToNewOrders
	
		$scope.sendOrderToNewOrders=function(user_id,oldorderId){
			dataObj={
				user_id		: user_id,
				oldorderId	: oldorderId
			};
			$http.post(webServiceUrl+'order',dataObj)
			.success(function(response) {
				if(response.value==1){
					$('#sendOrderStatus'+oldorderId).html('');
					$('#sendOrderStatus'+oldorderId).append("Send SuccessFully.");
				}
			});
		}
		//end
		
	// Cancelled order function 
	
		$scope.cancelTomarrowOrder=function(tracking_id,status){
			var Cancelledorder_tracking_id=tracking_id;
			dataObj={
					compliantType	:	"Cancelled",
					complaint_id	:	"0",
					tracking_id		:	Cancelledorder_tracking_id
			};
			$http.put(webServiceUrl+'order/'+Cancelledorder_tracking_id,dataObj)
				.success(function(response) {
					if(response.value==1){
						if(status==2){
							$('#sendOrderStatus'+tracking_id).html('');
							$('#cancelTomarrow'+tracking_id).html('');
							$('#cancelTomarrow1'+tracking_id).html('');
							$('#sendSucc'+tracking_id).html('');
						}else{
							$('#cancelTomarrow1'+tracking_id).html('');
							$('#sendSucc'+tracking_id).html('');
						}
					}
				});
		}
		
	//End
   
	if(typeof sessionStorage["admin_user_id"]!='undefined'){
		$http.get(webServiceUrl+'all-renewed-orders/1')
		.success(function(response) {
			if(response.value==1){
				//$scope.getNotifications(user_id);
				var data=response.result;
				$.each(data, function (index,Object) {
					if(Object.prescription_upload_path!=""){
						var imagess=Object.prescription_upload_path;
						var images=imagess.split('**');
						data[index].preImageLength=images.length;
						if(images.length>0){
						  for(var i=0;i<1;i++){
							   if(images[i]!=null){
									data[index].preImage=uploadImgUrl+images[i];
								}else{
									data[index].preImage=uploadImgUrl+'default.jpg';
								}
							}
						}
					}else{
						data[index].preImage=uploadImgUrl+'default.jpg';
					}
					var pdetails=Object.prescription_details;
					var details=pdetails.split('**');
					if(details.length>0){
						for(var i=0;i<1;i++){
							if(typeof details[i]!='undefined'){
								var names=details[i].split('$$');
								data[index].Tabletname=names[0];
								data[index].Quantity=names[1];
								data[index].preLength=details.length;
							}
						}
					}
				});	
				$scope.tableParams = new ngTableParams({
					page: 1, 
					count: 10
				}, {
					total: data.length,
					getData: function($defer, params) {
						$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
					}
				});
			}else{
				var admin_user_id = JSON.parse(sessionStorage["admin_user_id"]);
				$scope.getNotifications(admin_user_id);
				$scope.emptyOrders=errornodata_message;
			}
		});
	}else{
		location.href="#";
	}
});

//Admin Change password
mcAdminApp.controller('changePasswordController', function($scope,$sce,$http) {
var user_id = JSON.parse(sessionStorage["admin_user_id"]);
	if(user_id!='undefined'){
		$scope.cpwdloading		=	$sce.trustAsHtml('');
		$scope.passwordcError='';
		$scope.cp = {};
		$scope.changePwdForm = function(cwdForm) {
			$scope.cpwdloading		=	$sce.trustAsHtml('<img src="images/ajax-loader.gif"/>');
			var cpwdObj=this.cp;
			if(cpwdObj.newPassword != cpwdObj.cnf_password){
				$scope.cpwdloading		=	$sce.trustAsHtml('');
				$scope.passwordcError	=	Change_errorconfirm_password;
			}else{
				$http.put(webServiceUrl+'changepassword/'+user_id,cpwdObj)
				.success(function(response) {
					$scope.cpwdloading		=	$sce.trustAsHtml('');
					$scope.passwordcError	=	'';
					if(response.value=='1'){
						$('#success_alert').show();
						$scope.successcDiv		= Change_successpassword_message;
						$("html, body").animate({ scrollTop: 0 }, 600);
						$('#success_alert').delay(3000).fadeOut('slow');
						$scope.cp.old_password="";
						$scope.cp.newPassword="";
						$scope.cp.cnf_password="";
					}else{
						$('#error_alert').show();
						$scope.errorDiv		= Changepassword_error_message;
						$("html, body").animate({ scrollTop: 0 }, 600);
						$('#error_alert').delay(3000).fadeOut('slow');
					}
				});
			}
		}
	}else{
		location.href="#";
	}
});

//Renewal orders 

mcAdminApp.controller('RenewalOrdersController', function($scope,$sce,$http,ngTableParams,ngDialog,$compile) {
	$scope.allPriscription		=	$sce.trustAsHtml('');
	$scope.allDetails			=	$sce.trustAsHtml('');
	$scope.index 				=   0;
	$scope.openPopups = function(type,user_m_id) {
	$http.get(webServiceUrl+'getprescription/'+user_m_id+'-0')
		.success(function(response) {
			var viewDetailes="";
			var viewallImages=[];
			var pdata=response.result;
			var viewAll='<tr><th>Tablet name</th><th>Quantity</th></tr>';
			$.each(pdata, function (index,Object) {
				//All Tabletes Pop up
				var prdetails=Object.prescription_details;
				var detailss=prdetails.split('**');
				if(detailss.length>0){
					for(var i=0;i<=(detailss.length-1);i++){
						var namess=detailss[i].split('$$');
						viewAll+='<tr><th>'+namess[0]+'</th>'+'<th>'+namess[1]+'</th></tr>';
					}
				}
				//End
				//All Order Details Pop Up
				if(Object.auto_renewal==0 || Object.auto_renewal==null){
					var auto_renewal='No';
				}else{
					var auto_renewal='Yes';
				}
				if(Object.each_days==0 || Object.auto_renewal==null){
					var each_days='No';
				}else{
					var each_days=Object.each_days;
				}
				if(Object.delivered_date=="" || Object.delivered_date==null){
					var deliverdDate="Not delivered";
				}else{
					var deliverdDate=Object.delivered_date;
				}
				if(Object.immediate==0 || Object.immediate==null){
					var immidiate='Not Immidiate';
				}else{
					var immidiate='Yes';
				}
				if(Object.availabletime==0 || Object.availabletime==null){
					var availabletime='Not Mention';
				}else{
					var availabletime=Object.availabletime;
				}
				viewDetailes+='<tr><th>Tracking Id</th><th>'+Object.user_medicine_order_id+'</th></tr>'+
					'<tr><th>Auto renewal </th><th>'+auto_renewal+'</th></tr>'+
					'<tr><th>Days</th><th>'+each_days+'</th></tr>'+
					'<tr><th>Delivered date</th><th>'+deliverdDate+'</th></tr>'+
					'<tr><th>Landmark </th><th>'+Object.landmark+'</th></tr>'+
					'<tr><th>Phone number </th><th>'+Object.phone+'</th></tr>'+
					'<tr><th>Alternative phone number</th><th>'+Object.alterphone+'</th></tr>'+
					'<tr><th>Address</th><th>'+Object.address+'</th></tr>'+
					'<tr><th>Immidiate</th><th>'+immidiate+'</th></tr>'+
					'<tr><th>Available time</th><th>'+availabletime+'</th></tr>';
				//End
				//All Prescription Images Pop Up
					var imagesss=Object.prescription_upload_path;
					var imagespre=imagesss.split('**');
					if(imagespre.length>0){
						for(var img=0;img<=(imagespre.length)-1;img++){
							viewallImages[img]=uploadImgUrl+imagespre[img];
						}
					}
				//End
			});
			$scope.allPriscription		=	$sce.trustAsHtml(viewAll);
			$scope.allDetails		=	$sce.trustAsHtml(viewDetailes);
			$scope.images = viewallImages;
			if(type==1){
				var openPopupId="viewPriscription.html";
			}else if(type==2){
				var openPopupId="viewDetails.html";
			}else if(type==3){
				var openPopupId="viewAllPreImages.html";
			}
			ngDialog.open({
				template: openPopupId,
				className: 'ngdialog-theme-plain',
				scope:$scope
			});
		});
	}
	$scope.updateTsPrevious = function() {
		$scope.tsPrevious = +new Date();
	}
	$scope.updateTsNext = function() {
		$scope.tsNext = +new Date();
	}
	//cancelled auto renewal function
	$scope.cancelautorenewalFun=function(tracking_id,autorenuval,status){
	var user_id = JSON.parse(sessionStorage["admin_user_id"]);
		var dataObj = {
						tracking_id		:  tracking_id,
						auto_renewal	:  autorenuval,
						user_id			:  user_id,
						hid_value		:  "ORDER"
					  };
		$http.put(webServiceUrl+'renuwalorder/'+tracking_id,dataObj)
		.success(function(response) {
			if(response.value=1){
				if(status==0){
					if(autorenuval==0){
						//$('#auto'+tracking_id).html('No');
						var cancelHtml='<a href="javascript:void(0)" ng-click ="cancelautorenewalFun('+tracking_id+',1,0)">Enable Auto Renewal/</a>';
						var emt = $compile(cancelHtml)($scope);
						$('#cancelshowhide'+tracking_id).html('');
						$('#cancelshowhide'+tracking_id).append(emt);
					}else{
						//$('#auto'+tracking_id).html('Yes');
						cancelHtml='<a href="javascript:void(0)" ng-click ="cancelautorenewalFun('+tracking_id+',0,0)">Cancel Auto Renewal /</a>';
						emt = $compile(cancelHtml)($scope);
						$('#cancelshowhide'+tracking_id).html('');
						$('#cancelshowhide'+tracking_id).append(emt);
					}
				}else{
					if(autorenuval==0){
						//$('#auto'+tracking_id).html('No');
						var cancelHtml='<a href="javascript:void(0)" ng-click ="cancelautorenewalFun('+tracking_id+',1,1)">Enable Auto Renewal/</a>';
						var emt = $compile(cancelHtml)($scope);
						$('#cancelautostatushide'+tracking_id).html('');
						$('#cancelautostatushide'+tracking_id).append(emt);
					}else{
						//$('#auto'+tracking_id).html('Yes');
						cancelHtml='<a href="javascript:void(0)" ng-click ="cancelautorenewalFun('+tracking_id+',0,1)">Cancel Auto Renewal /</a>';
						emt = $compile(cancelHtml)($scope);
						$('#cancelautostatushide'+tracking_id).html('');
						$('#cancelautostatushide'+tracking_id).append(emt);
					}
				}
			}
		});
	}
	// Cancelled order function 
	
		$scope.cancelOrder=function(tracking_id,status){
			var Cancelledorder_tracking_id=tracking_id;
			dataObj={
					compliantType	:	"Cancelled",
					complaint_id	:	"0",
					tracking_id		:	Cancelledorder_tracking_id
			};
			$http.put(webServiceUrl+'order/'+Cancelledorder_tracking_id,dataObj)
				.success(function(response) {
					if(response.value==1){
						if(status==0){
							$('#cancelStatus'+tracking_id).html('');
							$('#cancelRewalOrder'+tracking_id).html('');
							$('#cancelshowhide'+tracking_id).html('');
							$('#cancelStatus'+tracking_id).append('Cancelled');
						}else if(status==2){
							$('#cancelStatus'+tracking_id).html('');
							$('#cancelRewalOrder1'+tracking_id).html('');
							$('#cancelautostatushide'+tracking_id).html('');
							$('#cancelStatus'+tracking_id).append('Cancelled');
						}else{
							
							$('#cancelStatus'+tracking_id).html('');
							$('#cancelRewalOrder2'+tracking_id).html('');
							$('#cancelStatus'+tracking_id).append('Cancelled');
						}
					}
				});
		}
		
	//End
	
	if(typeof sessionStorage["admin_user_id"]!='undefined'){
		var user_id = JSON.parse(sessionStorage["admin_user_id"]);
		$http.get(webServiceUrl+'all-renewed-orders')
		.success(function(response) {
			if(response.value==1){
				//$scope.getNotifications(user_id);
				var data=response.result;
				$.each(data, function (index,Object) {
					if(Object.prescription_upload_path!=""){
						var imagess=Object.prescription_upload_path;
						var images=imagess.split('**');
						data[index].preImageLength=images.length;
						if(images.length>0){
						  for(var i=0;i<1;i++){
							   if(images[i]!=null){
									data[index].preImage=uploadImgUrl+images[i];
								}else{
									data[index].preImage=uploadImgUrl+'default.jpg';
								}
							}
						}
					}else{
						data[index].preImage=uploadImgUrl+'default.jpg';
					}
					var pdetails=Object.prescription_details;
					var details=pdetails.split('**');
					if(details.length>0){
						for(var i=0;i<1;i++){
							if(typeof details[i]!='undefined'){
								var names=details[i].split('$$');
								data[index].Tabletname=names[0];
								data[index].Quantity=names[1];
								data[index].preLength=details.length;
							}
						}
					}
				});	
				$scope.tableParams = new ngTableParams({
					page: 1,
					count: 10
				}, {
					total: data.length,
					getData: function($defer, params) {
						$defer.resolve(data.slice((params.page() - 1) * params.count(), params.page() * params.count()));
					}
				});
			}else{
				//$scope.getNotifications(user_id);
				$scope.emptyOrders=errornodata_message;
			}
		});
	}else{
		location.href="#";
	}
});

